<template>
  <div>
    <baidu-map :center="center" :zoom="zoom" @ready="handler" style="height:20rem"  :scroll-wheel-zoom='true' @click="getClickInfo">
      <bm-geolocation anchor="BMAP_ANCHOR_TOP_RIGHT" :showAddressBar="false" :autoLocation="true"
                      @locationSuccess="getLoctionSuccess" @locationError="getLocationError">
      </bm-geolocation>
      <!-- 自定义定位图标覆盖物 -->
      <bm-marker :position="autoLocationPoint" v-if="initLocation">
      </bm-marker>
      <bm-control :offset="{width: '10px', height: '10px'}">
        <bm-auto-complete v-model="addressKeyword" style="width:8rem;display:inline-block" :sugStyle="{zIndex: 999999}">
          <input type="text" style="margin-left:0.5rem;margin-top:1.4rem;" placeholder="请输入您要找的地址" class="serachinput">
        </bm-auto-complete>
      </bm-control>
      <bm-local-search :keyword="addressKeyword" :auto-viewport="true" style="width:0px;height:0px;overflow: hidden;"></bm-local-search>
    </baidu-map>
    <div class="footer-fixed">
      <div class="btn-bottom">
        <div class="btn-bottom-left" @click="cancel">
          <span class="btn-bottom-style">取消</span>
        </div>
        <div class="btn-bottom-right" @click="confirm">
          <span class="btn-bottom-right-style">确认</span>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
  import { isEmpty,toast} from '../../tools'
  export default {
    name: "selectMap",
    data(){
      return{
        status:0,
        addressKeyword:'',
        realName:'',
        phone:'',
        imgHeader:'',
        mod_img:'',
        center: {
          lat:30.545151,
          lng:104.079337,
          address:"TCL通讯成都有限公司"
        },
        zoom:12,
        autoLocationPoint: {lng: 0, lat: 0},
        initLocation: false,
      }
    },
    mounted: function () {
      if (this.$route.query.status === 1 || this.$route.query.status === '1') {
        this.status = 1
        if (this.$route.query.id === 1 || this.$route.query.id === '1') {
          this.carOwner = 1
        } else {
          this.carOwner = 0
        }
        console.log('carOwner： ' + this.carOwner)
        this.phone = this.$route.query.phone
      }else {
        this.status = 0

      }
      let reg_latitude = localStorage.getItem('reg_latitude')
      let reg_longitude = localStorage.getItem('reg_longitude');
      let reg_address = localStorage.getItem('reg_address');
      console.log('that：reg_latitude ', reg_latitude)
      console.log('that：reg_longitude ' , reg_longitude)
      console.log('that：reg_address ' , reg_address)

      if (localStorage.getItem('reg_latitude') !== 0) {
        console.log('that：center1 ' + JSON.stringify(this.center))
        this.center.lat = localStorage.getItem('reg_latitude')
      }
      if (localStorage.getItem('reg_longitude')!==0) {
        console.log('that：center2 ' + JSON.stringify(this.center))
        this.center.lng = localStorage.getItem('reg_longitude')
      }
      if (!localStorage.getItem('reg_address')) {
        console.log('that：center3 ' + JSON.stringify(this.center))
        this.center.address = localStorage.getItem('reg_address')
      }
      console.log('that：center ' + JSON.stringify(this.center))
    },
    methods:{
      /***
       * 地图点击事件。
       */
      getClickInfo (e) {
        this.center.lng = e.point.lng
        this.center.lat = e.point.lat
      // 自定义覆盖物
        this.autoLocationPoint.lng=e.point.lng
        this.autoLocationPoint.lat=e.point.lat
        console.log('e:', e)	// 如果这里直接使用this是不行的
        console.log("lng:"+this.center.lng+",lat:"+this.center.lat);
        let geoc = new BMap.Geocoder();

        let that=this;
        geoc.getLocation(e.point, function(rs) {
          if(!rs){
            return;
          }
          let addComp = rs.addressComponents;

          console.log("addComp", addComp);
          if (!isEmpty(addComp.province)) {
            that.center.address = addComp.province;
          }
          if (!isEmpty(addComp.city)) {
            that.center.address =" " +  addComp.city;
          }
          if (!isEmpty(addComp.district)) {
            that.center.address =" " +  addComp.district;
          }
          if (!isEmpty(addComp.street)) {
            that.center.address =" " +  addComp.street;
          }
          if (!isEmpty(addComp.street_number)) {
            that.center.address =" " +  addComp.street_number;
          }

          console.log('address', that.center.address)	// 如果这里直接使用this是不行的

        });

      },
      /***
       * 确认
       */
      confirm: function () {
        console.log(this.center)
        if(this.center.lat === 30.545151 && this.center.lng === 104.079337){
          toast("请选择您的位置！");
          return;
        }
        if(this.status === 1){
          this.$router.push({
            name:"userInfo",
            query:{
              status:1,
              id:this.carOwner,
              phone:this.phone,
              isFromSelectMap:true
            }
          })
        }else {
          this.$router.push({
            name:'register',
            query:{
              isFromSelectMap:true
            }
          })

        }
        localStorage.setItem("reg_longitude",this.center.lng)
        localStorage.setItem("reg_latitude",this.center.lat)
        localStorage.setItem("reg_address",this.center.address)
        console.log('address', that.center.address)	// 如果这里直接使用this是不行的

      },
      /***
       * 取消
       */
      cancel: function () {
        // this.showMapComponent = false
        // this.$emit('cancel', this.showMapComponent)
        if(this.status === 1){
          this.$router.push({
            name:"userInfo",
            query:{
              status:1,
              id:this.carOwner,
              phone:this.phone,
              isFromSelectMap:true
            }
          })
        }else {
          this.$router.push({
            name:'register',
            query:{
              isFromSelectMap:true
            }
          })
        }
      },

      getLoctionSuccess(){

      },
      getLocationError(){

      },
      infoWindowClose(marker) {
        marker.showFlag = false
      },
      infoWindowOpen(marker) {
        marker.showFlag = true
      },
      handler ({BMap, map}) {
        // TODO: 触摸移动时触发此事件 此时开启可以拖动。虽然刚初始化该地图不可以拖动，但是可以触发拖动事件。
        map.addEventListener("touchmove", function (e) {
          map.enableDragging();
        });
        // TODO: 触摸结束时触发次此事件  此时开启禁止拖动
        map.addEventListener("touchend", function (e) {
          map.disableDragging();
        });
        // 初始化地图 禁止拖动   注：虽禁止拖动，但是可以出发拖动事件
        map.disableDragging();

        let _this = this;	// 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
        let geolocation = new BMap.Geolocation();
        if(localStorage.getItem('reg_latitude') === 0 && localStorage.getItem('reg_longitude') === 0){
          geolocation.getCurrentPosition(function(r){
            console.log("geolocation",r)
            if(this.getStatus() === BMAP_STATUS_SUCCESS) {
              console.log("accuracy",r.accuracy)
              if(r.accuracy != null ){
                _this.center = {
                  lng: r.longitude,
                  lat: r.latitude,
                  address:""
                };
                let addComp = r.address;
                if (!isEmpty(addComp.province)) {
                  _this.center.address = addComp.province;
                }
                if (!isEmpty(addComp.city)) {
                  _this.center.address =" " +  addComp.city;
                }
                if (!isEmpty(addComp.district)) {
                  _this.center.address =" " +  addComp.district;
                }
                if (!isEmpty(addComp.street)) {
                  _this.center.address =" " +  addComp.street;
                }
                if (!isEmpty(addComp.street_number)) {
                  _this.center.address =" " +  addComp.street_number;
                }
              }
            }
            // console.log(_this.center)
            _this.autoLocationPoint = {lng: _this.center.lng, lat: _this.center.lat};		// 自定义覆盖物
            _this.initLocation = true;
          },{enableHighAccuracy: true});

        }else {
          this.autoLocationPoint = {lng: this.center.lng, lat: this.center.lat};		// 自定义覆盖物
          this.initLocation = true;
        }
      }
    },
    components:{


    }
  }

</script>

<style scoped lang="less" >
  .footer-fixed{
    position:fixed;
    left:0;
    right:0;
    bottom:0;
    top:80%;
    .btn-bottom{
      width:100%;
      height:2rem;
      margin-top:0.5rem;
      //border:1px solid blue;
      /*background:rgba(0,0,0,0.3);*/

      display:flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-around;
      .btn-bottom-left{
        width:2rem;
        height:0.8rem;
        border-radius:0.8rem;
        background:#ff5a00;
        display:flex;
        align-items: center;
        justify-content: center;
        .btn-bottom-style{
          font-size:0.35rem;
          color:#fff;
        }
      }
      .btn-bottom-right{
        width:2rem;
        height:0.8rem;
        border-radius:0.8rem;
        background:#ff5a00;
        display:flex;
        align-items: center;
        justify-content: center;
        .btn-bottom-right-style{
          font-size:0.35rem;
          color:#fff;
        }
      }

    }
  }

  .serachinput{
    width: 100%;
    box-sizing: border-box;
    padding: 0.09rem;
    border: 1px solid #dddee1;
    line-height: 0.7rem;
    font-size: 0.38rem;
    height: 0.7rem;
    color: #333;
    position: relative;
    border-radius: 0.1rem;
    -webkit-box-shadow: #666 0px 0px 0.1rem;
    -moz-box-shadow: #666 0px 0px 0.1rem;
    box-shadow: #666 0px 0px 0.1rem;
  }
</style>
